package io.techery.progresshint.addition;

import io.techery.progresshint.ProgressHintDelegate;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentTreeObserver;

public class ProgressHintScrollController implements ComponentTreeObserver.ScrollChangedListener {
    private final Component container;
    private final ProgressHintDelegate delegate;

    /**
     * register
     *
     * @param container container
     * @param holder holder
     * @return ProgressHintScrollController
     */
    public static ProgressHintScrollController register(Component container,
            ProgressHintDelegate.SeekBarHintDelegateHolder holder) {
        ProgressHintScrollController controller = new ProgressHintScrollController(container, holder);
        container.getComponentTreeObserver().addScrolledListener(controller);
        return controller;
    }

    /**
     * ProgressHintScrollController Instance
     *
     * @param container container
     * @param holder holder
     */
    public ProgressHintScrollController(Component container, ProgressHintDelegate.SeekBarHintDelegateHolder holder) {
        this.container = container;
        this.delegate = holder.getHintDelegate();
    }

    @Override
    public void onScrolled() {
        if (delegate.isPopupVisible()) {
            if (!delegate.isWidgetFullyVisible(container)) {
                delegate.hidePopup();
            }
        } else if (delegate.isPopupAlwaysShown() && delegate.isWidgetFullyVisible(container)) {
            delegate.showPopup();
        } else {
            delegate.hidePopup();
        }
    }

    /**
     * dispose
     */
    public void dispose() {
        container.getComponentTreeObserver().removeScrolledListener(this);
    }
}
